﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyProject : MonoBehaviour
{
    public GameObject master;
    public float speed;
    public Vector2 velocity;
    private SpriteRenderer spriteRender;

    protected Rigidbody2D _rb2d;
    protected Collider2D _col2d;

    public FaceDir dir;

    void Awake()
    {
        _rb2d = this.GetComponent<Rigidbody2D>();
        _col2d = this.GetComponent<Collider2D>();
        spriteRender = this.GetComponent<SpriteRenderer>();
    }

    /// <summary>
    /// 发射子弹，传入参数：初始速度，伤害
    /// </summary>
    public void InitProject(FaceDir dir, GameObject master)
    {
        this.master = master;
        this.dir = dir;

        if (dir == FaceDir.FACE_DIR_RIGHT)
        {
            velocity = Vector2.right * speed;
        }
        else if (dir == FaceDir.FACE_DIR_LEFT)
        {
            velocity = Vector2.left * speed;
            spriteRender.flipX = true;
        }
        Destroy(this.gameObject, 10f);
    }

    void FixedUpdate()
    {
        Vector2 pos = _rb2d.position;
        pos = pos + velocity * Time.fixedDeltaTime;
        _rb2d.MovePosition(pos);
    }

    //销毁子弹
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("ProjectDestroyer"))
        {
            Destroy(this.gameObject);
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.transform.CompareTag("Player1"))
        {
            Destroy(this.gameObject);
        }
        else if (collision.transform.CompareTag("Player2"))
        {
            Destroy(this.gameObject);
        }
    }
}
